package com.lsq.baseadmin.modules.manage.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsq.baseadmin.modules.manage.entity.Role;
import com.lsq.baseadmin.modules.manage.entity.RoleMenu;
import com.lsq.baseadmin.modules.manage.mapper.RoleMapper;
import com.lsq.baseadmin.modules.manage.mapper.RoleMenuMapper;
import com.lsq.baseadmin.modules.manage.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lsq
 * @since 2020-10-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {


    private RoleMenuMapper roleMenuMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(int id) {
        // 删除角色要把关联表的菜单删除
        baseMapper.deleteById(id);

        QueryWrapper<RoleMenu> roleMenuWrapper = new QueryWrapper<>();
        roleMenuWrapper.eq("role_id", id);
        roleMenuMapper.delete(roleMenuWrapper);
    }

    @Override
    public List<Role> list(Role role) {
        QueryWrapper<Role> wrapper = createWrapper(role);
        return baseMapper.selectList(wrapper);
    }

    @DS("slave")
    @Override
    public List<Role> listSlave(Role role) {
        QueryWrapper<Role> wrapper = createWrapper(role);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void updateMenu(int id, Integer[] menuIds) {
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", id);
        roleMenuMapper.delete(wrapper);

        if (menuIds.length < 1) {
            return;
        }
        List<RoleMenu> list = new ArrayList<>();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(id);
            roleMenu.setMenuId(menuId);

            list.add(roleMenu);
        }
        roleMenuMapper.insertBatch(list);
    }

    private QueryWrapper<Role> createWrapper(Role role) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if(null == role) {
            return wrapper;
        }

        if(StringUtils.hasText(role.getName())) {
            wrapper.like("name", role.getName());
        }
        return wrapper;
    }

    @Resource
    public void setRoleMenuMapper(RoleMenuMapper roleMenuMapper) {
        this.roleMenuMapper = roleMenuMapper;
    }
}
